﻿CREATE PROCEDURE [dbo].[yaf_user_find](
                @BoardID  INT,
                @Filter   BIT,
                @UserName NVARCHAR(50)  = NULL,
                @Email    NVARCHAR(50)  = NULL)
AS
    BEGIN
        IF @Filter <> 0
        BEGIN
            IF @UserName IS NOT NULL
            SET @UserName = '%' + @UserName + '%'
            SELECT   a.*,
                     IsGuest = (SELECT COUNT(1)
                                FROM   yaf_UserGroup x,
                                       yaf_Group y
                                WHERE  x.UserID = a.UserID
                                AND x.GroupID = y.GroupID
                                AND (y.Flags & 2) <> 0)
            FROM     yaf_User a
            WHERE    a.BoardID = @BoardID
            AND (@UserName IS NOT NULL 
                 AND a.Name LIKE @UserName)
             OR (@Email IS NOT NULL 
                 AND Email LIKE @Email)
            ORDER BY a.Name
        END
        ELSE
        BEGIN
            SELECT a.UserID,
                   IsGuest = (SELECT COUNT(1)
                              FROM   yaf_UserGroup x,
                                     yaf_Group y
                              WHERE  x.UserID = a.UserID
                              AND x.GroupID = y.GroupID
                              AND (y.Flags & 2) <> 0)
            FROM   yaf_User a
            WHERE  a.BoardID = @BoardID
            AND ((@UserName IS NOT NULL 
                  AND a.Name = @UserName)
                  OR (@Email IS NOT NULL 
                      AND Email = @Email))
        END
    END


